using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using DocumentCreationSystem.Services;
using DocumentCreationSystem.Models;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;

namespace DocumentCreationSystem
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        private IHost? _host;

        public static IServiceProvider ServiceProvider { get; private set; } = null!;

        protected override async void OnStartup(StartupEventArgs e)
        {
            try
            {
                Console.WriteLine("开始启动应用程序...");
                Console.WriteLine($"当前时间: {DateTime.Now}");
                Console.WriteLine($"工作目录: {Environment.CurrentDirectory}");

                // 创建主机
                Console.WriteLine("创建主机...");
                _host = CreateHostBuilder(e.Args).Build();

                // 设置ServiceProvider
                Console.WriteLine("设置ServiceProvider...");
                ServiceProvider = _host.Services;

                // 初始化数据存储
                Console.WriteLine("初始化数据存储...");
                await InitializeDataStorageAsync();

                // 初始化主题
                Console.WriteLine("初始化主题...");
                await InitializeThemeAsync();

                // 启动主机
                Console.WriteLine("启动主机...");
                await _host.StartAsync();

                // 验证服务注册
                Console.WriteLine("验证服务注册...");
                ValidateServices();

                // 初始化AI服务配置
                Console.WriteLine("初始化AI服务配置...");
                await InitializeAIServiceConfigAsync();

                // 创建并显示主窗口
                Console.WriteLine("创建主窗口...");
                var mainWindow = _host.Services.GetRequiredService<MainWindow>();
                Console.WriteLine("显示主窗口...");
                mainWindow.Show();

                Console.WriteLine("应用程序启动完成");
                base.OnStartup(e);
            }
            catch (Exception ex)
            {
                var detailedMessage = $"应用程序启动失败:\n\n错误类型: {ex.GetType().Name}\n错误消息: {ex.Message}\n\n堆栈跟踪:\n{ex.StackTrace}";
                if (ex.InnerException != null)
                {
                    detailedMessage += $"\n\n内部异常: {ex.InnerException.Message}";
                    if (ex.InnerException.InnerException != null)
                    {
                        detailedMessage += $"\n\n更深层异常: {ex.InnerException.InnerException.Message}";
                    }
                }

                // 输出到控制台
                Console.WriteLine(detailedMessage);

                // 显示错误对话框
                try
                {
                    MessageBox.Show(detailedMessage, "错误详情", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                catch
                {
                    Console.WriteLine("无法显示错误对话框");
                }

                Shutdown(1);
            }
        }

        protected override async void OnExit(ExitEventArgs e)
        {
            Console.WriteLine("应用程序正在退出...");
            if (_host != null)
            {
                await _host.StopAsync();
                _host.Dispose();
            }
            base.OnExit(e);
        }

        private static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((context, config) =>
                {
                    var basePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
                                   ?? Directory.GetCurrentDirectory();
                    config.SetBasePath(basePath);
                    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                })
                .ConfigureServices((context, services) =>
                {
                    // 注册数据存储服务（替代数据库）
                    services.AddSingleton<IDataStorageService, JsonDataStorageService>();

                    // 注册服务
                    services.AddScoped<IProjectService, ProjectService>();
                    services.AddScoped<IDocumentService, DocumentService>();
                    services.AddSingleton<IThinkingChainService, ThinkingChainService>();
                    services.AddSingleton<IThemeService, ThemeService>();
                    services.AddSingleton<IProjectHistoryService, ProjectHistoryService>();
                    services.AddSingleton<IAIService>(provider =>
                        new AIServiceManager(
                            provider.GetRequiredService<IConfiguration>(),
                            provider.GetRequiredService<ILogger<AIServiceManager>>(),
                            provider.GetRequiredService<IThinkingChainService>(),
                            provider));
                    services.AddScoped<IProjectToolsService, ProjectToolsService>();
                    // 注册AI工具服务
                    services.AddScoped<IAIToolsService, AIToolsService>();
                    // 使用BGE-M3向量化服务，支持LM Studio的text-embedding-bge-m3模型
                    services.AddScoped<IVectorService, BGEEmbeddingService>();
                    services.AddScoped<IFileMonitorService, SimpleFileMonitorService>();
                    services.AddScoped<INovelCreationService, NovelCreationService>();
                    services.AddScoped<IAIModelConfigService, AIModelConfigService>();
                    services.AddScoped<IVectorModelConfigService, VectorModelConfigService>();
                    services.AddScoped<AutomatedChapterCreationService>();
                    services.AddScoped<WorldSettingService>();
                    services.AddScoped<WritingProgressService>();
                    services.AddScoped<TimelineService>();
                    services.AddScoped<NetworkRecoveryService>();
                    services.AddScoped<ResumableCreationService>();

                    // 增强写书功能服务
                    services.AddScoped<EnhancedChapterContentService>();
                    services.AddScoped<CharacterUpdateService>();
                    services.AddScoped<ChapterOutlineUpdateService>();
                    services.AddScoped<StepByStepWritingService>(provider =>
                        new StepByStepWritingService(
                            provider.GetRequiredService<ILogger<StepByStepWritingService>>(),
                            provider.GetRequiredService<IAIService>(),
                            provider.GetRequiredService<INovelCreationService>(),
                            provider.GetRequiredService<IDataStorageService>(),
                            provider.GetRequiredService<WorldSettingService>(),
                            provider.GetRequiredService<ChapterContinuityService>(),
                            provider.GetRequiredService<EnhancedWorldSettingManager>(),
                            provider.GetRequiredService<IFileNamingService>(),
                            provider.GetRequiredService<ContentQualityService>(),
                            provider.GetRequiredService<UnifiedChapterSaveService>(),
                            provider.GetService<IProjectToolsService>(),
                            provider.GetService<NetworkRecoveryService>(),
                            provider.GetService<ResumableCreationService>(),
                            provider));
                    services.AddScoped<AgentToolService>();
                    services.AddScoped<ChapterContinuityService>();
                    services.AddScoped<EnhancedWorldSettingManager>();

                    // 注册自主规划相关服务
                    services.AddScoped<AutonomousPlanningService>();
                    services.AddScoped<EnhancedIntentRecognizer>();
                    services.AddScoped<CharacterPlanningEngine>();
                    services.AddScoped<CharacterRelationshipAnalyzer>();
                    services.AddScoped<CharacterDevelopmentPlanner>();
                    services.AddScoped<WorkflowOrchestrationEngine>();
                    services.AddScoped<WorkflowStepGenerator>();
                    services.AddScoped<WorkflowOptimizer>();
                    services.AddScoped<WorkflowExecutor>();
                    services.AddScoped<ExecutionMonitoringService>();
                    services.AddScoped<AdaptiveExecutionController>();
                    services.AddScoped<IBookBasicInfoService, BookBasicInfoService>();
                    services.AddScoped<IToolApiConfigService, ToolApiConfigService>();
                    services.AddScoped<OllamaModelPullService>();
                    services.AddScoped<ContentQualityService>();
                    services.AddScoped<ChapterContentRepairService>();
                    services.AddScoped<ProjectCleanupService>();

                    // 注册配置管理服务
                    services.AddScoped<IPromptConfigService, PromptConfigService>();
                    services.AddScoped<IWritingWorkflowConfigService, WritingWorkflowConfigService>();

                    // 注册文件命名服务
                    services.AddSingleton<IFileNamingService, FileNamingService>();

                    // 注册统一章节保存服务
                    services.AddScoped<UnifiedChapterSaveService>();

                    // 注册文档模板服务
                    services.AddSingleton<IDocumentTemplateService, DocumentTemplateService>();

                    // 注册文件格式服务
                    services.AddSingleton<IFileFormatService, FileFormatService>();

                    // 注册论文写作服务
                    services.AddScoped<IPaperWritingService, PaperWritingService>();

                    // 注册专利交底书写作服务
                    services.AddScoped<IPatentDisclosureService, PatentDisclosureService>();

                    // 注册SOP写作服务
                    services.AddScoped<ISOPWritingService, SOPWritingService>();

                    // 注册系统监控服务
                    services.AddSingleton<ISystemMonitorService, SystemMonitorService>();

                    // 注册HttpClient
                    services.AddHttpClient();

                    // 注册主窗口
                    services.AddTransient<MainWindow>();

                    // 配置日志
                    services.AddLogging(builder =>
                    {
                        builder.AddConsole();
                        builder.AddDebug();
                        builder.SetMinimumLevel(LogLevel.Information);
                    });
                });

        private async Task InitializeDataStorageAsync()
        {
            if (_host == null) return;

            using var scope = _host.Services.CreateScope();
            var dataStorage = scope.ServiceProvider.GetRequiredService<IDataStorageService>();
            var logger = scope.ServiceProvider.GetRequiredService<ILogger<App>>();

            try
            {
                logger.LogInformation("开始初始化数据存储...");

                // 加载现有数据
                await dataStorage.LoadAsync();

                logger.LogInformation("数据存储初始化完成");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "数据存储初始化失败");
                throw;
            }
        }

        private async Task InitializeThemeAsync()
        {
            if (_host == null) return;

            using var scope = _host.Services.CreateScope();
            var themeService = scope.ServiceProvider.GetRequiredService<IThemeService>();
            var logger = scope.ServiceProvider.GetRequiredService<ILogger<App>>();

            try
            {
                logger.LogInformation("开始初始化主题...");

                // 从配置加载主题
                await themeService.LoadThemeFromConfigAsync();

                logger.LogInformation("主题初始化完成");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "主题初始化失败，使用默认主题");
                try
                {
                    await themeService.ResetToDefaultAsync();
                }
                catch (Exception resetEx)
                {
                    logger.LogError(resetEx, "重置默认主题也失败了");
                }
            }
        }

        private async Task InitializeAIServiceConfigAsync()
        {
            if (_host == null) return;

            using var scope = _host.Services.CreateScope();
            var logger = scope.ServiceProvider.GetRequiredService<ILogger<App>>();

            try
            {
                logger.LogInformation("开始初始化AI服务配置...");

                var aiService = scope.ServiceProvider.GetRequiredService<IAIService>();
                if (aiService is AIServiceManager aiServiceManager)
                {
                    await aiServiceManager.InitializeFromConfigFileAsync();
                    logger.LogInformation("AI服务配置初始化完成");
                }
                else
                {
                    logger.LogWarning("AI服务不是AIServiceManager类型，跳过配置初始化");
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "AI服务配置初始化失败");
                // 不抛出异常，让程序继续运行
            }
        }

        private void ValidateServices()
        {
            if (_host == null) return;

            using var scope = _host.Services.CreateScope();
            var logger = scope.ServiceProvider.GetRequiredService<ILogger<App>>();

            try
            {
                // 验证所有必需的服务都能正确创建
                logger.LogInformation("验证服务注册...");

                var aiService = scope.ServiceProvider.GetRequiredService<IAIService>();
                logger.LogInformation("IAIService 验证成功");

                var projectService = scope.ServiceProvider.GetRequiredService<IProjectService>();
                logger.LogInformation("IProjectService 验证成功");

                var documentService = scope.ServiceProvider.GetRequiredService<IDocumentService>();
                logger.LogInformation("IDocumentService 验证成功");

                var vectorService = scope.ServiceProvider.GetRequiredService<IVectorService>();
                logger.LogInformation("IVectorService 验证成功");

                var novelCreationService = scope.ServiceProvider.GetRequiredService<INovelCreationService>();
                logger.LogInformation("INovelCreationService 验证成功");

                var aiToolsService = scope.ServiceProvider.GetRequiredService<IAIToolsService>();
                logger.LogInformation("IAIToolsService 验证成功");

                logger.LogInformation("所有服务验证完成");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "服务验证失败");
                throw;
            }
        }
    }
}
